package com.xunfei.socket.Service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import kotlinx.coroutines.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket

class SocketClientService: Service(){
    private val binder = LocalBinder()
    private var socket: Socket? = null
    private var writer: PrintWriter? = null
    private var reader: BufferedReader? = null
    private var job: Job? = null
    private var messageListener: ((String) -> Unit)? = null
    private var connectionListener: ((Boolean) -> Unit)? = null

    inner class LocalBinder : Binder() {
        val service: SocketClientService get() = this@SocketClientService
    }

    override fun onBind(intent: Intent?): IBinder = binder

    override fun onDestroy() {
        super.onDestroy()
        disconnect()
    }

    // 连接到服务器
    fun connect(host: String, port: Int) {
        job = CoroutineScope(Dispatchers.IO).launch {
            try {
                socket = Socket(host, port)
                writer = PrintWriter(socket?.outputStream, true)
                reader = BufferedReader(InputStreamReader(socket?.inputStream))

                withContext(Dispatchers.Main) {
                    connectionListener?.invoke(true)
                }

                // 开始接收消息
                receiveMessages()
            } catch (e: Exception) {
                Log.e("SocketClient", "连接失败: ${e.message}")
                withContext(Dispatchers.Main) {
                    connectionListener?.invoke(false)
                }
            }
        }
    }

    // 发送消息
    fun sendMessage(message: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                writer?.println(message)
                Log.d("SocketClient", "发送: $message")
            } catch (e: Exception) {
                Log.e("SocketClient", "发送失败: ${e.message}")
                withContext(Dispatchers.Main) {
                    connectionListener?.invoke(false)
                    disconnect()
                }
            }
        }
    }

    // 接收消息
    private suspend fun receiveMessages() {
        try {
            var line: String?
            while (socket?.isConnected == true) {
                line = reader?.readLine()
                if (line != null) {
                    withContext(Dispatchers.Main) {
                        messageListener?.invoke(line)
                    }
                } else {
                    // 连接关闭
                    withContext(Dispatchers.Main) {
                        connectionListener?.invoke(false)
                    }
                    break
                }
            }
        } catch (e: Exception) {
            Log.e("SocketClient", "接收消息失败: ${e.message}")
            withContext(Dispatchers.Main) {
                connectionListener?.invoke(false)
            }
        } finally {
            disconnect()
        }
    }

    // 断开连接
    fun disconnect() {
        job?.cancel()
        try {
            reader?.close()
            writer?.close()
            socket?.close()
        } catch (e: Exception) {
            Log.e("SocketClient", "关闭连接失败: ${e.message}")
        }
        reader = null
        writer = null
        socket = null
    }

    // 设置消息监听器
    fun setMessageListener(listener: (String) -> Unit) {
        messageListener = listener
    }

    // 设置连接状态监听器
    fun setConnectionListener(listener: (Boolean) -> Unit) {
        connectionListener = listener
    }

    // 检查连接状态
    fun isConnected(): Boolean = socket?.isConnected == true

}